<template>
  <!-- 修改外层容器阴影和圆角 -->
  <div
    v-if="visible"
    class="fixed inset-0 bg-black/30 backdrop-blur-sm z-50 flex items-center justify-center p-4"
  >
    <div
      class="bg-white text-gray-800 rounded-xl shadow-2xl max-w-2xl w-full relative transition-all duration-300 max-h-[90vh] flex flex-col overflow-hidden"
    >
      <!-- 关闭按钮样式优化 -->
      <button
        @click="close"
        class="absolute top-4 right-4 text-gray-500 hover:text-gray-700 transition-colors p-1.5 hover:bg-gray-100 rounded-full"
      >
        &times;
      </button>

      <div class="p-6 flex-1 overflow-auto">
        <!-- 标题样式优化 -->
        <h2 class="text-2xl font-bold mb-6 text-gray-800 border-b pb-4">
          {{ isEdit ? "编辑作品" : "新建作品" }}
        </h2>

        <form @submit.prevent="submitForm" class="flex-1 flex flex-col">
          <!-- 输入框组样式优化 -->
          <div class="space-y-6 flex-1 overflow-auto">
            <div>
              <label class="block text-sm font-semibold mb-2 text-gray-600"
                >书名</label
              >
              <input
                v-model="form.name"
                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
                required
              />
            </div>

            <div>
              <label class="block text-sm font-semibold mb-2 text-gray-600"
                >分类</label
              >
              <select
                v-model="form.category"
                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all appearance-none bg-[url('')] bg-no-repeat bg-[center_right_1rem]"
                v-if="categories.length > 0"
              >
                <!-- 选项样式优化 -->
                <option
                  v-for="cat in categories"
                  :value="cat.id"
                  :key="cat.id"
                  class="p-2 hover:bg-blue-50"
                >
                  {{ cat.name }}
                </option>
              </select>
              <div v-else class="text-red-500 text-sm">暂无分类数据</div>
            </div>

            <!-- 复选框组布局优化 -->
            <div class="grid grid-cols-2 gap-4">
              <label
                class="flex items-center space-x-3 p-3 hover:bg-gray-50 rounded-lg cursor-pointer"
              >
                <input
                  type="checkbox"
                  v-model="form.is_published"
                  class="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <span class="text-gray-700">是否发布</span>
              </label>
              <label
                class="flex items-center space-x-3 p-3 hover:bg-gray-50 rounded-lg cursor-pointer"
              >
                <input
                  type="checkbox"
                  v-model="form.is_free"
                  class="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <span class="text-gray-700">是否免费</span>
              </label>
            </div>

            <div>
              <label class="block text-sm font-semibold mb-2 text-gray-600"
                >封面图片</label
              >
              <div class="relative group">
                <input
                  type="file"
                  @change="handleFileUpload"
                  accept="image/*"
                  class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                />
                <div
                  class="w-full px-4 py-10 border-2 border-dashed border-gray-200 rounded-lg group-hover:border-blue-500 transition-colors text-center"
                >
                  <template v-if="currentCoverUrl">
                    <img
                      :src="currentCoverUrl"
                      class="mb-2 max-w-full max-h-64 mx-auto object-contain"
                    />
                    <span class="text-green-600 font-medium">当前封面</span>
                  </template>
                  <template v-else-if="form.cover_image">
                    <span class="text-green-600 font-medium"
                      >已选择文件：{{ form.cover_image.name }}</span
                    >
                  </template>
                  <template v-else>
                    <span class="text-blue-600 font-medium">点击上传图片</span>
                    <span class="text-gray-500 ml-2">或拖拽文件至此</span>
                  </template>
                </div>
              </div>
              <div v-if="currentCoverUrl" class="mt-2 text-sm text-gray-500">
                上传新文件将替换当前封面
              </div>
            </div>

            <div>
              <label class="block text-sm font-semibold mb-2 text-gray-600"
                >简介</label
              >
              <textarea
                v-model="form.review"
                class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all h-32 resize-none"
              ></textarea>
            </div>
          </div>

          <!-- 按钮组间距和样式优化 -->
          <div class="border-t pt-4 px-6 pb-6 bg-white">
            <div class="flex justify-end gap-3">
              <button
                type="button"
                @click="close"
                class="px-6 py-2.5 text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg font-medium transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                class="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors shadow-sm hover:shadow-md"
              >
                {{ isEdit ? "保存修改" : "创建作品" }}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import showMessage from "@/utils/message.js";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    // 新增：编辑时传递书籍ID
    bookId: {
      type: [String, Number],
      default: null,
    },
  },
  data() {
    return {
      form: {
        name: "",
        category: "",
        is_published: false,
        is_free: true,
        review: "无",
        cover_image: null,
      },
      categories: [],
      currentCoverUrl: "",
    };
  },
  watch: {
    // 监听visible变化，打开时加载数据
    visible(newVal) {
      if (newVal) this.initForm();
    },
  },
  methods: {
    async initForm() {
      try {
        // 加载分类数据
        const res = await axios.get("/api/category/");
        this.categories = res.data.results;
        // 重置封面预览
        this.currentCoverUrl = "";

        if (this.isEdit && this.bookId) {
          const res = await axios.get(`/api/book/${this.bookId}/`, {
            headers: { Authorization: "JWT " + localStorage.getItem("token") },
          });
          this.form = {
            ...res.data,
            category: res.data.category?.id || "", // 确保分类ID正确绑定
            cover_image: null, // 重置文件输入
          };
          // 显示现有封面
          if (res.data.cover_image_url) {
            this.currentCoverUrl = res.data.cover_image_url;
          }
        }

        // 编辑模式加载书籍数据
        if (this.isEdit && this.bookId) {
          const res = await axios.get(`/api/book/${this.bookId}/`, {
            headers: {
              Authorization: "JWT " + localStorage.getItem("token"),
            },
          });
          this.form = { ...res.data };
        } else {
          // 新建模式重置表单
          this.form = {
            name: "",
            category: "",
            is_published: false,
            is_free: true,
            review: "无",
            cover_image: null,
          };
        }
      } catch (error) {
        console.error("初始化失败:", error);
        showMessage("数据加载失败");
      }
    },

    async submitForm() {
      try {
        const formData = new FormData();

        // 转换表单数据为FormData格式
        Object.keys(this.form).forEach((key) => {
          const value = this.form[key];
          if (value !== null && value !== undefined) {
            // 处理文件字段
            if (key === "cover_image") {
              if (value instanceof File) {
                formData.append(key, value);
              } else if (this.isEdit && !value) {
                // 编辑模式下允许清除封面
                formData.append(key, "");
              }
            } else {
              formData.append(key, value);
            }
          }
        });

        const config = {
          headers: {
            Authorization: "JWT " + localStorage.getItem("token"),
            "Content-Type": "multipart/form-data",
          },
        };

        if (this.isEdit) {
          // 使用PATCH方法支持部分更新
          await axios.patch(`/api/book/${this.bookId}/`, formData, config);
        } else {
          const bookRes = await axios.post("/api/book/", formData, config);
          await axios.post(
            "/api/owned/",
            { book_id: bookRes.data.id },
            {
              headers: {
                Authorization: "JWT " + localStorage.getItem("token"),
              },
            }
          );
        }
        this.$emit("success");
        this.close();
        showMessage(this.isEdit ? "修改成功" : "创建成功", "info");
      } catch (error) {
        console.error("操作失败:", error);
        showMessage(
          `操作失败: ${error.response?.data?.detail || "请检查输入"}`
        );
      }
    },

    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      this.form.cover_image = file;

      // 生成临时预览URL
      if (file.type.startsWith("image/")) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.currentCoverUrl = e.target.result;
        };
        reader.readAsDataURL(file);
      } else {
        this.currentCoverUrl = "";
        showMessage("请选择图片文件", "error");
        this.form.cover_image = null;
      }
    },

    close() {
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style scoped>
/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}
::-webkit-scrollbar-track {
  @apply bg-gray-100 rounded;
}
::-webkit-scrollbar-thumb {
  @apply bg-gray-400 rounded hover:bg-gray-500;
}
</style>
